from werkzeug.security import generate_password_hash, check_password_hash

from apps.db import db
from apps.db.base_class import BaseModel, ModelMixin, db_session_commit


class User(BaseModel, ModelMixin):

    username = db.Column(db.String(100), index=True, comment='用户名')
    mobile = db.Column(db.String(12), index=True, unique=True, comment='手机号')
    email = db.Column(db.String(300), index=True, unique=True, comment='邮箱')
    password_hash = db.Column(db.String(200), nullable=False, comment='密码哈希')
    login_time = db.Column(db.Integer, comment='登陆时间,时间戳到秒级')

    # foreignkey
    role_id = db.Column(db.Integer, db.ForeignKey('role.id'), index=True, nullable=False, comment='外键角色id')

    # relationships
    admin_user = db.relationship('AdminUser', backref='user', uselist=False)
    role = db.relationship('Role', backref='users')

    @property
    def password(self):
        raise AttributeError('password only can write')

    @password.setter
    def password(self, plain):
        self.password_hash = generate_password_hash(plain)

    def verify_password(self, password):
        return check_password_hash(self.password_hash, password)

    def save(self):
        # 保存数据
        if self.mobile or self.email:
            db.session.add(self)
            db_session_commit()
            return self
        else:
            raise Exception('mobile and email are None')
    
    @property
    def creator_name(self):
        user = User.get(id=self.creator)
        return user.username
